package com.adouteam.simple.wechat.msg.event;

import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.base.WeixinUrls;
import com.adouteam.simple.wechat.msg.AllMsg;
import com.adouteam.simple.wechat.msg.MessageAble;
import com.adouteam.simple.wechat.service.ResponseService;
import com.adouteam.simple.wechat.tool.LinkTool;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 关注事件
 *
 * @author buxianglong
 */
public class SubscribeEventMsg extends EventMsg implements MessageAble{
    private static final String EVENT = "subscribe";

    private String eventKey;

    public String getEventKey() {
        return eventKey;
    }

    public void setEventKey(String eventKey) {
        this.eventKey = eventKey;
    }

    public static String getBindUrl(WechatConstants wechatConstants){
        String bindUrl = WeixinUrls.replace(WeixinUrls.AUTHORIZE_URL, wechatConstants, new HashMap<String, String>(3){
            private static final long serialVersionUID = -1784970754640079253L;

            {
                put("REDIRECT_URI", LinkTool.encodeUrl(WeixinUrls.DOMAIN_NAME + "weixin/help/login"));
                put("SCOPE", WechatConstants.USER_INFO_SCOPE_USERINFO);
                put("STATE", WechatConstants.USER_INFO_STATE);
            }
        });
        return bindUrl;
    }

    public static String getAccountUrl(WechatConstants wechatConstants){
        String accountUrl = WeixinUrls.replace(WeixinUrls.AUTHORIZE_URL, wechatConstants, new HashMap<String, String>(3){
            private static final long serialVersionUID = 8219981512539265367L;

            {
                put("REDIRECT_URI", LinkTool.encodeUrl(WeixinUrls.DOMAIN_NAME + "action/newWeixin/registerNewAccount"));
                put("SCOPE", WechatConstants.USER_INFO_SCOPE_USERINFO);
                put("STATE", WechatConstants.USER_INFO_STATE);
            }
        });
        return accountUrl;
    }

    @Override
    public boolean isMe(AllMsg allMsg){
        if(null == allMsg){
            return false;
        }
        return MSG_TYPE.equalsIgnoreCase(allMsg.getMsgType())
                && EVENT.equalsIgnoreCase(allMsg.getEvent())
                && StringUtils.isBlank(allMsg.getEventKey());
    }

    @Override
    public void copyProperties(AllMsg allMsg){
        this.setFromUserName(allMsg.getFromUserName());
        this.setToUserName(allMsg.getToUserName());
        this.setCreateTime(allMsg.getCreateTime());
        this.setMsgType(allMsg.getMsgType());
        this.setMsgId(allMsg.getMsgId());
        this.setEventKey(allMsg.getEventKey());
    }

    @Override
    public void process(HttpServletResponse response){
        ResponseService.responseBlank(response);
    }

    @Override
    public String toString(){
        return "SubscribeEventMsg{} " + super.toString();
    }
}
